package com.ruoyi.central.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.ruoyi.central.domain.TopCentralTaskCmd;
import com.ruoyi.central.publisher.PublisherUtils;
import com.ruoyi.central.publisher.event.ProcessStepEvent;
import com.ruoyi.central.service.ITopCentralArtProcessService;
import com.ruoyi.central.service.ITopCentralTaskCmdService;
import com.ruoyi.common.enums.SignEnum;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.service.ServiceUtils;
import com.ruoyi.common.validation.group.InsertGroup;
import com.ruoyi.common.validation.group.UpdateGroup;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.bean.SelectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.central.domain.TopCentralProcessStep;
import com.ruoyi.central.service.ITopCentralProcessStepService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.validation.group.UpdateBatchGroup;
import com.ruoyi.common.core.domain.StateVo;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 工序Controller
 * 
 * @author ruoyi
 * @date 2022-03-02
 */
@Controller
@RequestMapping("/central/centralProcessStep")
public class TopCentralProcessStepController extends BaseController
{
    private String prefix = "central/centralProcessStep";

    @Autowired
    private ITopCentralProcessStepService topCentralProcessStepService;
    @Autowired
    private ITopCentralArtProcessService artProcessService;
    @Autowired
    private ITopCentralTaskCmdService taskCmdService;

    @RequiresPermissions("central:centralProcessStep:view")
    @GetMapping()
    public String centralProcessStep()
    {
        return prefix + "/centralProcessStep";
    }

    /**
     * 查询工序列表
     */
    @RequiresPermissions("central:centralProcessStep:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(TopCentralProcessStep topCentralProcessStep)
    {
        startPage();
        List<TopCentralProcessStep> list = topCentralProcessStepService.selectList(topCentralProcessStep);

        ServiceUtils.complete(list,artProcessService,(artProcessMap,processStep)->processStep.setArtProcess(artProcessMap.get(processStep.getArtProcessId())));

        ServiceUtils.complete(list,taskCmdService,(taskCmdMap,processStep)->{
            if(StringUtils.isNotEmpty(processStep.getTaskCmdIds())){
                List<Integer> taskCmdIds = Arrays.stream(StringUtils.split(processStep.getTaskCmdIds(),',')).map(Integer::parseInt).collect(Collectors.toList());
                List<TopCentralTaskCmd> taskCmdList = new ArrayList<>();
                taskCmdIds.forEach(taskCmdId->{
                    if(taskCmdMap.containsKey(taskCmdId)){
                        taskCmdList.add(taskCmdMap.get(taskCmdId));
                    }
                });
                processStep.setTaskCmdList(taskCmdList);
            }

        });


        return getDataTable(list);
    }

    /**
     * 查询简单的工序列表 用于select选择器
     */
    @GetMapping("/simpleList")
    @ResponseBody
    public AjaxResult simpleList(TopCentralProcessStep topCentralProcessStep){

        Collection<TopCentralProcessStep> topCentralProcessStepList = topCentralProcessStepService.selectAllMap().values();

        return AjaxResult.success(SelectUtils.buildSelectList(topCentralProcessStepList,TopCentralProcessStep::getId,TopCentralProcessStep::getName));
    }

    /**
     * 获取工序详细信息
     */
    @RequiresPermissions("central:centralProcessStep:query")
    @GetMapping(value = "/{id}")
    @ResponseBody
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return AjaxResult.success(topCentralProcessStepService.selectById(id));
    }

    /**
     * 获取自增排序值
     * @param topCentralProcessStep 过滤条件
     * @return
     */
    @GetMapping("/getIncrementWeight")
    @ResponseBody
    public AjaxResult getIncrementWeight(TopCentralProcessStep topCentralProcessStep){
        int weigth = topCentralProcessStepService.getMaxOfWeight(topCentralProcessStep);
        return AjaxResult.success(++weigth);
    }

    /**
     * 下载工序导入模板
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<TopCentralProcessStep> util = new ExcelUtil<>(TopCentralProcessStep.class);
        util.importTemplateExcel(response, "工序数据");
    }

    /**
     * 导入工序数据
     * @param file 工序数据文件
     * @param updateSupport 是否为更新
     */
    @Log(title = "工序", businessType = BusinessType.IMPORT)
    @RequiresPermissions("central:centralProcessStep:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<TopCentralProcessStep> util = new ExcelUtil<>(TopCentralProcessStep.class);
        List<TopCentralProcessStep> topCentralProcessStepList = util.importExcel(file.getInputStream());

        if(updateSupport){
            if(topCentralProcessStepService.updateBatchById(topCentralProcessStepList)){
                return AjaxResult.success("导入工序数据覆盖成功！");
            }
            return AjaxResult.error("导入工序数据覆盖失败！");
        }
        if(topCentralProcessStepService.insertBatch(topCentralProcessStepList)){
            return AjaxResult.success("导入工序数据新增成功！");
        }
        return AjaxResult.error("导入工序数据新增失败！");
    }

    /**
     * 导出工序列表
     */
    @RequiresPermissions("central:centralProcessStep:export")
    @Log(title = "工序", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TopCentralProcessStep topCentralProcessStep)
    {
        List<TopCentralProcessStep> list = topCentralProcessStepService.selectList(topCentralProcessStep);
        ExcelUtil<TopCentralProcessStep> util = new ExcelUtil<TopCentralProcessStep>(TopCentralProcessStep.class);
        return util.exportExcel(list, "工序数据");
    }

    /**
     * 新增工序
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存工序
     */
    @RequiresPermissions("central:centralProcessStep:add")
    @Log(title = "工序", businessType = BusinessType.INSERT)
    @PostMapping
    @ResponseBody
    public AjaxResult addSave(@Validated(InsertGroup.class) @RequestBody TopCentralProcessStep topCentralProcessStep)
    {
        return toAjax(topCentralProcessStepService.insert(topCentralProcessStep));
    }

    /**
     * 修改工序
     */
    @RequiresPermissions("central:centralProcessStep:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
        TopCentralProcessStep topCentralProcessStep = topCentralProcessStepService.selectById(id);
        mmap.put("topCentralProcessStep", topCentralProcessStep);
        return prefix + "/edit";
    }

    /**
     * 修改保存工序
     */
    @RequiresPermissions("central:centralProcessStep:edit")
    @Log(title = "工序", businessType = BusinessType.UPDATE)
    @PutMapping
    @ResponseBody
    public AjaxResult editSave(@Validated(UpdateGroup.class) @RequestBody TopCentralProcessStep topCentralProcessStep)
    {
        PublisherUtils.publishEvent(ProcessStepEvent.class,topCentralProcessStep, SignEnum.UPDATE);

        return toAjax(topCentralProcessStepService.updateById(topCentralProcessStep));
    }

    /**
     * 修改工序 状态 根据 ids 主键
     */
    @RequiresPermissions("central:centralProcessStep:edit")
    @Log(title = "工序", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStateByIds")
    @ResponseBody
    public AjaxResult updateStateByIds(@Validated(value= UpdateBatchGroup.class)@RequestBody StateVo<Integer> stateVo)
    {
        PublisherUtils.publishEvent(ProcessStepEvent.class,
                ServiceUtils.toBeanList(stateVo.getIds(),TopCentralProcessStep.class,
                        (processStep,processStepId)->{processStep.setId(processStepId);processStep.setState(stateVo.getState());})
                , SignEnum.UPDATE);

        return toAjax(topCentralProcessStepService.updateStateByIds(stateVo.getIds(),stateVo.getState()));
    }

    /**
     * 删除工序
     */
    @RequiresPermissions("central:centralProcessStep:remove")
    @Log(title = "工序", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ResponseBody
    public AjaxResult deleteByIds(@PathVariable("ids") List<Integer> ids)
    {
            return toAjax(topCentralProcessStepService.deleteByIds(ids));
    }
}
